﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Hirham.OpenMI.Engine
{
  public class FileDataController : Hirham.OpenMI.Engine.IDataController
  {

    public string ExchangePath { get; private set; }


    public FileDataController(string ExchangePath)
    {
      this.ExchangePath = ExchangePath;
    }


    public string GetHirhamData(out DateTime HirhamTime)
    {
      HirhamTime = DateTime.Now;
//      FileInfo f = new FileInfo(Path.Combine(ExchangePath, "hirham_data_ready.txt"));
      
      while (!File.Exists(Path.Combine(ExchangePath, "hirham_data_ready.txt")))
      {
        // wait for HIRHAM to produce data (sleep 1 sec)
        System.Threading.Thread.Sleep(100);
      }

      while (!GetHirhamTime(out HirhamTime))
        // wait for HIRHAM to stop writing in file
        System.Threading.Thread.Sleep(100);

      string data;
      using (StreamReader sr = new StreamReader(Path.Combine(ExchangePath,"hirham.out")))
      {
        data = sr.ReadToEnd();
      }

      File.Delete(Path.Combine(ExchangePath, "hirham_data_ready.txt"));
      File.Delete(Path.Combine(ExchangePath, "hirham_data_ready_timestep.txt"));
      return data;
    }

    private bool GetHirhamTime(out DateTime currentHirhamTime)
    {
      string firstLine;
      bool done = false;

      StreamReader reader=null;
      try
      {
          string tempname = Path.Combine(ExchangePath, "hirham_data_ready_timestep.txt");
          reader = new StreamReader(tempname);
          firstLine = reader.ReadLine().Trim();
//          firstLine = firstLine.Trim().Substring(2).Trim(); //Removes the first characters + any spaces in the end

          // Extract the date (the format is "N" "HIRHAM" "write" "at" "(now:)" "YYYY" "MM" "DD" "HH" "MM" "SEC"  
          // i.e. the date and time is stored at array indices 5-10.
          string[] vstr = firstLine.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
          currentHirhamTime = new DateTime(Convert.ToInt32(vstr[5]), Convert.ToInt32(vstr[6]), Convert.ToInt32(vstr[7]), Convert.ToInt32(vstr[8]), Convert.ToInt32(vstr[9]), Convert.ToInt32(vstr[10]));

          currentHirhamTime = DateTime.SpecifyKind(currentHirhamTime, DateTimeKind.Utc);
          done = true;

      }
      catch (Exception e)
      {
          currentHirhamTime = DateTime.MinValue;
      }
      finally
      {
          if (reader != null)
              reader.Dispose();

      }
      return done;
    }


    public void SetHirhamData(string Data, string QuantityID)
    {
      string filename = Path.Combine(ExchangePath, "openmi_data_ready.txt");

      while (File.Exists(filename))
      {
        // wait for HIRHAM to grap the data (sleep 0.1 sec)
        System.Threading.Thread.Sleep(100);
      }

      string outputfile= Path.Combine(ExchangePath, QuantityID + ".in");

      using (StreamWriter writer = new StreamWriter(outputfile))
      {
        writer.Write(Data);
      }
    }


    public void NoMoreOutputInTimestep(int currentTimeStepNumber, DateTime CurrentTime)
    {
      string filename = Path.Combine(ExchangePath, "openmi_data_ready.txt");
      using (StreamWriter sw = new StreamWriter(filename))
      {
        sw.WriteLine("   " + currentTimeStepNumber.ToString());
        sw.WriteLine(CurrentTime.ToUniversalTime().ToString());
      }
    }
  }
}
